import axios from 'axios'

// 创建axios实例
const api = axios.create({
  baseURL: '/api',
  timeout: 30000,
  headers: {
    'Content-Type': 'application/json'
  }
})

// 请求拦截器
api.interceptors.request.use(
  (config) => {
    // 添加认证token
    const token = localStorage.getItem('token')
    if (token) {
      config.headers.Authorization = `Bearer ${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    return response
  },
  (error) => {
    if (error.response?.status === 401) {
      // token过期，清除本地存储
      localStorage.removeItem('token')
      localStorage.removeItem('refreshToken')
      // 可以在这里重定向到登录页
    }
    return Promise.reject(error)
  }
)

// 发送HTTP请求的工具函数
export const sendHttpRequest = async (requestConfig) => {
  try {
    const { method, url, headers, params, body, bodyType, formFields } = requestConfig
    
    // 构建请求配置
    const config = {
      method: method.toLowerCase(),
      url: url.startsWith('http') ? url : url,
      headers: {},
      timeout: 30000
    }
    
    // 处理请求头
    if (headers && headers.length > 0) {
      headers.forEach(header => {
        if (header.key && header.value) {
          config.headers[header.key] = header.value
        }
      })
    }
    
    // 处理GET请求参数
    if (method === 'GET' && params && params.length > 0) {
      const queryParams = {}
      params.forEach(param => {
        if (param.key && param.value) {
          queryParams[param.key] = param.value
        }
      })
      config.params = queryParams
    }
    
    // 处理POST/PUT/PATCH请求体
    if (['post', 'put', 'patch'].includes(method.toLowerCase())) {
      if (bodyType === 'json') {
        try {
          config.data = body ? JSON.parse(body) : {}
        } catch (e) {
          config.data = body || {}
        }
      } else if (bodyType === 'form') {
        const formData = new FormData()
        if (formFields && formFields.length > 0) {
          formFields.forEach(field => {
            if (field.key && field.value) {
              formData.append(field.key, field.value)
            }
          })
        }
        config.data = formData
        // 移除Content-Type，让浏览器自动设置
        delete config.headers['Content-Type']
      } else if (bodyType === 'raw') {
        config.data = body || ''
      }
    }
    
    // 发送请求
    const response = await axios(config)
    
    return {
      status: response.status,
      statusText: response.statusText,
      headers: response.headers,
      data: response.data,
      config: response.config
    }
    
  } catch (error) {
    if (error.response) {
      // 服务器响应了错误状态码
      throw new Error(`请求失败: ${error.response.status} - ${error.response.statusText}`)
    } else if (error.request) {
      // 请求已发出但没有收到响应
      throw new Error('网络错误: 无法连接到服务器')
    } else {
      // 其他错误
      throw new Error(`请求配置错误: ${error.message}`)
    }
  }
}

// 用户相关API
export const userApi = {
  // 获取用户列表
  getUsers: (params) => api.get('/users', { params }),
  
  // 获取单个用户
  getUser: (id) => api.get(`/users/${id}`),
  
  // 创建用户
  createUser: (data) => api.post('/users', data),
  
  // 更新用户
  updateUser: (id, data) => api.put(`/users/${id}`, data),
  
  // 删除用户
  deleteUser: (id) => api.delete(`/users/${id}`)
}

// 认证相关API
export const authApi = {
  // 用户登录
  login: (credentials) => api.post('/auth/login', credentials),
  
  // 用户注册
  register: (userData) => api.post('/auth/register', userData),
  
  // 刷新token
  refreshToken: (refreshToken) => api.post('/auth/refresh', { refreshToken }),
  
  // 用户登出
  logout: () => api.post('/auth/logout'),
  
  // 获取当前用户信息
  getCurrentUser: () => api.get('/auth/me')
}

// 文件相关API
export const fileApi = {
  // 文件上传
  uploadFile: (file, options = {}) => {
    const formData = new FormData()
    formData.append('file', file)
    
    if (options.category) {
      formData.append('category', options.category)
    }
    if (options.description) {
      formData.append('description', options.description)
    }
    
    return api.post('/files/upload', formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })
  },
  
  // 获取文件列表
  getFiles: (params) => api.get('/files', { params }),
  
  // 下载文件
  downloadFile: (fileId) => api.get(`/files/${fileId}/download`, {
    responseType: 'blob'
  }),
  
  // 删除文件
  deleteFile: (fileId) => api.delete(`/files/${fileId}`)
}

// 通用API
export const commonApi = {
  // 健康检查
  healthCheck: () => api.get('/health'),
  
  // 获取系统信息
  getSystemInfo: () => api.get('/system/info'),
  
  // 获取API统计
  getApiStats: () => api.get('/system/stats')
}

export default api
